﻿using AiQiuQuan.Sport.Core;
using AiQiuQuan.Sport.Core.WechatPayV3;
using SKIT.FlurlHttpClient.Wechat.TenpayV3;
using SKIT.FlurlHttpClient.Wechat.TenpayV3.Models;
using AiQiuQuan.Sport.Model.Enums;
using AiQiuQuan.Sport.Model.Models;
using AiQiuQuan.Sport.WebApi.Core;
using AiQiuQuan.Sport.WebApi.Entities;
using AiQiuQuan.Sport.WebApi.Repositories;
using MapsterMapper;
using Microsoft.Extensions.Options;

namespace AiQiuQuan.Sport.WebApi.Services.Impl
{
    /// <summary>
    /// 转账
    /// </summary>
    public class TransferAccountService : ITransferAccountService
    {
        private readonly IMapper _mapper;
        private readonly IOptions<WechatPayOption> _options;
        private readonly IWechatPayV3HttpClientFactory _wechatPayV3HttpClientFactory;
        private readonly ITransferAccountRepository _transferAccountRepository;

        /// <summary>
        /// ctor
        /// </summary>
        public TransferAccountService(
            IMapper mapper,
            IOptions<WechatPayOption> options,
            IWechatPayV3HttpClientFactory wechatPayV3HttpClientFactory,
            ITransferAccountRepository transferAccountRepository)
        {
            _mapper = mapper;
            _options = options;
            _wechatPayV3HttpClientFactory = wechatPayV3HttpClientFactory;
            _transferAccountRepository = transferAccountRepository;
        }

        /// <summary>
        /// 微信转账到零钱包
        /// </summary>
        public async Task<UnaryResult> WxTransferToWalletAsync(TransferAccountAddDto model)
        {
            var trnsferOrder = CreateTransferAccount(model);
            trnsferOrder.TransferType = TransferTypeEnum.WxWallet;
            var request = new CreateTransferBatchRequest
            {
                AppId = _options.Value.AppId,
                OutBatchNumber = trnsferOrder.OrderNo,
                BatchName = trnsferOrder.Remark,
                BatchRemark = trnsferOrder.Remark,
                TotalAmount = (int)(model.Amount * 100),
                TotalNumber = 1,
            };
            request.TransferDetailList.Add(new CreateTransferBatchRequest.Types.TransferDetail
            {
                OutDetailNumber = trnsferOrder.DetailNo,
                TransferAmount = request.TotalAmount,
                TransferRemark = trnsferOrder.Remark,
                OpenId = trnsferOrder.AccountId,
                UserName = model.Amount < 2000 ? null : trnsferOrder.AccountName
            });
            var wxPayClient = _wechatPayV3HttpClientFactory.Create();
            request = wxPayClient.EncryptRequestSensitiveProperty(request);
            var rep = await wxPayClient.ExecuteCreateTransferBatchAsync(request);
            if (rep.ErrorCode == "SYSTEM_ERROR")
            {
                await Task.Delay(500);
                rep = await wxPayClient.ExecuteCreateTransferBatchAsync(request);
            }

            if (!rep.IsSuccessful())
            {
                trnsferOrder.State = TransferStateEnum.Faild;
                trnsferOrder.FaildRemark = $"{rep.ErrorCode},{rep.ErrorMessage}";
            }

            trnsferOrder.ThirdTransferId = rep.BatchId;
            await _transferAccountRepository.AddAsync(trnsferOrder);

            if (trnsferOrder.State == TransferStateEnum.Faild)
            {
                return UnaryResult.Faild(10, $"微信转账失败:{trnsferOrder.FaildRemark}");
            }

            return UnaryResult.Succeed();
        }

        #region private methods
        /// <summary>
        /// 新增转账单
        /// </summary>
        private TransferAccountOrder CreateTransferAccount(TransferAccountAddDto model)
        {
            var entity = _mapper.Map<TransferAccountOrder>(model);
            entity.OrderNo = $"Wx{Tool.BuildPayOrderNo(model.BusinessType)}";
            entity.DetailNo = $"Wx{Tool.BuildPayOrderNo(model.BusinessType)}";
            entity.State = TransferStateEnum.Processing;
            return entity;
        }

        #endregion
    }
}
